package upload

import (
	"fmt"
	"github.com/labstack/echo"
	"net/http"
	"path/filepath"
	"strconv"
	"strings"
	"tacitus/library/file"
	"time"
)

/*
用来处理iceEditor上传的文件
 */
var FileType = []string{
	"jpg","jpeg","png","gif","bmp","exe","flv","swf","mkv","avi","rm","rmvb","mpeg","mpg","ogg","ogv","mov",
	"wmv","mp4","webm","mp3","wav","mid","rar","zip","tar","gz","7z","bz2","cab","iso","chm","doc","docx",
	"xls","xlsx","ppt","pptx","pdf","txt","md","xml","torrent",
}                                     // 可上传的文件类型
var FileSize int64 = 30 * 102400            // 可上传的文件大小
var FileFieldName = "file[]";           // 前端上传时使用的字段名称
var OnlineFieldName = "iceEditor-img" // 引用网络图片的字段名称

type File struct {
	Url string `json:"url"`
	Name string `json:"name"`
	Error interface{} `json:"error"` // 成功返回0,错误返回1或者字符串
}

func IceEditorUploadHandler(c echo.Context) error {
	res := make([]File, 0)
	// ice允许上传网络图片的地址
	if url := c.FormValue(OnlineFieldName); url != "" {
		name := filepath.Base(url)
		storage, browse := s.Path(fmt.Sprintf("%d", time.Now().Unix())+filepath.Ext(url))
		if err := file.Download(s, url, storage); err != "" {
			res = append(res, File{Name:name, Error:err})
		} else {
			res = append(res, File{Name:name, Url:browse, Error:0})
		}
	}
	form, _ := c.MultipartForm()
	fs := form.File[FileFieldName]
	for i, fh := range fs {
		if fh.Size > FileSize {
			res = append(res, File{Name:fh.Filename, Error: "文件大小超过上传限制"})
			continue
		}

		ext := strings.TrimPrefix(filepath.Ext(fh.Filename), ".")
		if !In(ext, FileType) {
			res = append(res, File{Name:fh.Filename, Error: "禁止上传该类型文件"})
			continue
		}

		name := fmt.Sprintf("%d", time.Now().Unix())
		if len(fs) > 1 {
			name += "_" + strconv.Itoa(i)
		}
		name += "."+ext

		storage, browse := s.Path(name)
		if err := file.Write(s, fh, storage); err != "" {
			res = append(res, File{Name:fh.Filename, Error:err})
		} else {
			res = append(res, File{Name:fh.Filename, Url:browse, Error:0})
		}
	}
	return c.JSON(http.StatusOK, res)
}

func In(target string, list []string) bool {
	for _, item := range list {
		if item == target {
			return true
		}
	}
	return false
}